package org.qh.ai.service.chat.impl;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.qh.ai.domain.ChatModel;
import org.qh.ai.domain.vo.ChatModelVo;
import org.qh.ai.enums.ChatModeType;
import org.qh.ai.handler.StreamingChatResponseHandler;
import org.qh.ai.service.request.ChatService;
import org.qh.ai.service.api.IChatModelService;
import org.qh.ai.service.chat.IChatService;
import org.qh.common.ai.entity.request.ChatRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;


/**
 * 阿里通义千问
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class QianWenAiChatServiceImpl implements IChatService {


    private final IChatModelService chatModelService;
    private final ChatService chatService;

    @Override
    public SseEmitter chat(ChatRequest chatRequest, SseEmitter emitter) {
        ChatModelVo chatModelVo = chatModelService.selectModelByName(chatRequest.getModel());

        ChatModel chatModel = ChatModel.builder()
            .modelName(chatModelVo.getModelName())
            .apiHost(chatModelVo.getApiHost())
            .apiKey(chatModelVo.getApiKey())
            .build();

        // 发送流式消息
        try {
            chatService.chat(chatModel, chatRequest.getMessages(), new StreamingChatResponseHandler() {
                @SneakyThrows
                @Override
                public void onPartialResponse(String partialResponse) {
                    emitter.send(partialResponse);
                    log.info("收到消息片段: {}", partialResponse);
                }

                @Override
                public void onCompleteResponse(String completeResponse) {
                    emitter.complete();
                    log.info("消息结束，完整消息: {}", completeResponse);
                }

                @Override
                public void onError(Throwable error) {
                    System.err.println("QianWen错误: " + error.getMessage());
                }
            });
        } catch (Exception e) {
            log.error("千问请求失败：{}", e.getMessage());
        }

        return emitter;

    }

    @Override
    public String getCategory() {
        return ChatModeType.QIANWEN.getCode();
    }


}
